package com.luo.ams.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luo.ams.mapper.PermissionMapper;
import com.luo.ams.mapper.RolePermissionMapper;
import com.luo.ams.service.IPermissionService;
import com.luo.common.exception.BBSServiceException;
import com.luo.common.restful.ResponseCode;
import com.luo.pojo.ams.dto.PermissionAddDTO;
import com.luo.pojo.ams.entity.Admin;
import com.luo.pojo.ams.entity.Permission;
import com.luo.pojo.ams.entity.RolePermission;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.swing.plaf.ButtonUI;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author bin.cn
 * @since 2023-01-19
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {

    @Autowired
    private PermissionMapper permissionMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public void add(PermissionAddDTO permissionAddDTO) {
        if (permissionAddDTO.getName()==null||permissionAddDTO.getValue()==null){
            throw new BBSServiceException(ResponseCode.BAD_REQUEST,"参数不能为空");
        }
        QueryWrapper<Permission> wrapper = new QueryWrapper<>();
        wrapper.eq("name",permissionAddDTO.getName());
        Permission permission = permissionMapper.selectOne(wrapper);
        if (permission!=null){
            throw new BBSServiceException(ResponseCode.CONFLICT,"名称冲突");
        }
        permission = new Permission();
        BeanUtils.copyProperties(permissionAddDTO,permission);
        permissionMapper.insert(permission);

    }

    @Transactional
    @Override
    public void deleteById(Long id) {
        if (id==null){
            throw new BBSServiceException(ResponseCode.BAD_REQUEST,"参数不能为空");
        }
        Permission permission = permissionMapper.selectById(id);
        //不存在不允许删除
        if (permission==null){
            throw new BBSServiceException(ResponseCode.NOT_FOUND,"管理员不存在");
        }
        permissionMapper.deleteById(id);

        QueryWrapper<RolePermission> rolePermissionQueryWrapper = new QueryWrapper<>();
        rolePermissionQueryWrapper.eq("permission_id",id);
        rolePermissionMapper.delete(rolePermissionQueryWrapper);
    }
}
